package com.stdio.modle;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import android.content.ContentResolver;
import android.content.Context;
import android.database.Cursor;
import android.net.Uri;
import android.provider.CallLog;

public class CallHistoryImpl implements IActionCallLog {

	
	private Context context;
	private ContentResolver contentResolver;
	private Uri uri = CallLog.Calls.CONTENT_URI;
	private String[] projection = new String[]{			
			CallLog.Calls.NUMBER,
			CallLog.Calls.CACHED_NAME,
			CallLog.Calls.TYPE, 
			CallLog.Calls.DATE,
			CallLog.Calls.DURATION
			};
	
	public CallHistoryImpl(Context context) {
		this.context = context;
		contentResolver = context.getContentResolver();
		// TODO Auto-generated constructor stub
	}	
	
	@Override
	public List<CallHistory> getCallList() {
		// TODO Auto-generated method stub
        Date date;
        List<CallHistory> list = new ArrayList<CallHistory>();
        Cursor cursor = contentResolver.query(uri, projection, null, null,CallLog.Calls.DEFAULT_SORT_ORDER);        
        while (cursor.moveToNext()) {
        	CallHistory tmp = new CallHistory();
        	tmp.setNumber(cursor.getString(0));
        	tmp.setName(cursor.getString(1));
        	tmp.setCalltype(cursor.getInt(2));
        	date = new Date(Long.parseLong(cursor.getString(3)));
        	tmp.setCalldate(date);
        	tmp.setDuration(cursor.getInt(4));
        	list.add(tmp);
		}
		if(!cursor.isClosed())
		{
			cursor.close();
		}
        return list;
	}

	@Override
	public List<CallHistory> queryCallList(String number) {
		// TODO Auto-generated method stub
        Date date;
        List<CallHistory> list = new ArrayList<CallHistory>();
        Cursor cursor = contentResolver.query(uri, projection, null, null,CallLog.Calls.DEFAULT_SORT_ORDER);        
        while (cursor.moveToNext()) {
        	if(cursor.getString(0).indexOf(number) != -1){
            	CallHistory tmp = new CallHistory();
            	tmp.setNumber(cursor.getString(0));
            	tmp.setName(cursor.getString(1));
            	tmp.setCalltype(cursor.getInt(2));
            	date = new Date(Long.parseLong(cursor.getString(3)));
            	tmp.setCalldate(date);
            	tmp.setDuration(cursor.getInt(4));
            	list.add(tmp);        		
        	}
		}
		if(!cursor.isClosed())
		{
			cursor.close();
		}
        return list;
	}

}
